<template>
  <div>
    <!-- 查询、新增、重置 -->
    <el-form :inline="true" :model="formInline" ref="formInline" class="demo-form-inline">
      <el-form-item prop="cardNum">
        <el-input oninput="value=value.replace(/[^\d]/g,'')" v-model="formInline.cardNum" placeholder="会员卡号"></el-input>
      </el-form-item>
      <el-form-item prop="name">
        <el-input v-model="formInline.name" placeholder="会员名称"></el-input>
      </el-form-item>
      <el-form-item prop="payType" style="width:110px;">
        <el-select v-model="formInline.payType" placeholder="支付类型">
          <el-option
            v-for="item in payTypeOptions"
            :key="item.type"
            :label="item.name"
            :value="item.type"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item required style="width:130px;">
        <el-col :span="11">
          <el-form-item prop="birthday" style="width:130px;">
            <el-date-picker
              type="date"
              placeholder="选择日期"
              v-model="formInline.birthday"
              style="width: 100%;"
            ></el-date-picker>
          </el-form-item>
        </el-col>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSubmit">查询</el-button>
        <el-button type="success" @click="addMember()">新增</el-button>
        <el-button type="warning" @click="resetForm('formInline')">重置</el-button>
      </el-form-item>
    </el-form>
    <!-- 查询、新增、重置 end-->

    <!-- 表格 -->
    <el-table :data="tableData" stripe style="width: 100%">
      <el-table-column fixed type="index" label="序号" width="50"></el-table-column>
      <el-table-column prop="cardNum" label="会员卡号" width="150"></el-table-column>
      <el-table-column prop="name" label="会员名称" width="80"></el-table-column>
      <el-table-column prop="birthday" label="会员生日" width="120"></el-table-column>
      <el-table-column prop="phone" label="手机号码" width="120"></el-table-column>
      <el-table-column prop="integral" label="可用积分" width="80"></el-table-column>
      <el-table-column prop="money" label="开卡金额" width="80"></el-table-column>
      <el-table-column prop="payType" label="支付类型" width="80"></el-table-column>
      <el-table-column prop="address" label="地址" width="250"></el-table-column>
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button type="info" size="mini" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
          <el-button size="mini" type="danger" @click="handleDelete(scope.$index, scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 表格 end-->

    <!-- 分页 -->
    <div class="block">
      <el-pagination
        background
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[10, 20, 30, 40]"
        :page-size="10"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>
    </div>
    <!-- 分页 end -->

    <!-- 新增功能、编辑共用对话框 -->
    <el-dialog
      class="el-dialog-aa"
      :title="form.id ? '编辑会员' : '添加会员'"
      :visible.sync="dialogFormVisible"
      width="500px"
      style="padding: 0 50px;"
    >
      <el-form
        :model="form"
        label-position="right"
        :rules="rules"
        ref="form"
        style="padding: 30px 60px 0px 20px;"
      >
        <el-form-item label="会员卡号" prop="cardNum" :label-width="formLabelWidth">
          <el-input oninput="value=value.replace(/[^\d]/g,'')" v-model="form.cardNum" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="会员名称" prop="name" :label-width="formLabelWidth">
          <el-input v-model="form.name" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="会员生日" :label-width="formLabelWidth">
          <el-input v-model="form.birthday" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="手机号码" prop="phone" :label-width="formLabelWidth">
          <el-input v-model.number="form.phone" />
        </el-form-item>

        <el-form-item label="可用积分" :label-width="formLabelWidth">
          <el-input oninput="value=value.replace(/[^\d]/g,'')" v-model="form.integral" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="开卡金额" :label-width="formLabelWidth">
          <el-input oninput="value=value.replace(/[^\d]/g,'')" v-model="form.money" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="支付方式" :label-width="formLabelWidth">
          <el-select v-model="form.payType" placeholder="请选择支付方式">
            <el-option
              v-for="item in payTypeOptions"
              :key="item.type"
              :label="item.name"
              :value="item.type"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="会员地址" :label-width="formLabelWidth">
          <el-input v-model="form.address" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="form.id?editMember('form'):submitInfo('form')">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 新增功能、编辑共用对话框 end-->
  </div>
</template>

<script>
import memberApi from "@/api/member";

export default {
  data() {
    //对话框手机认证
    var checkPhone = (rule, value, callback) => {
      if (!value) {
        return callback(new Error("手机号不能为空"));
      } else {
        const reg = /^1[3|4|5|7|8][0-9]\d{8}$/;
        // console.log(reg.test(value));
        if (reg.test(value)) {
          callback();
        } else {
          return callback(new Error("请输入正确的手机号"));
        }
      }
    };
    return {
      // 查询条件、重置
      formInline: {
        cardNum: "", //会员卡号
        name: "", //会员名称
        payType: "", //支付方式
        birthday: "" //会员生日
      },
      //查询中的日期选择
      rules: {
        date1: [
          {
            type: "date",
            required: true,
            message: "请选择日期",
            trigger: "change"
          }
        ]
      },
      //   表格 数据
      /**{
          cardNum: "1", //会员卡号
          name: "2", //会员名称
          birthday: "3",//会员生日
          phone: '4',//手机号码
          integral: '5',//可用积分
          money: '6',//开卡金额
          payType: "1", //支付方式
          address: '8' //地址
        } */
      tableData: [], //列表数据
      currentPage: 1, //当前第1页
      pagesize: 10, //每页显示条目个数
      total: 0, //总条目数
      payTypeOptions: [
        { type: "1", name: "现金" },
        { type: "2", name: "微信" },
        { type: "3", name: "支付宝" },
        { type: "4", name: "银行卡" }
      ], //支付类型
      dialogFormVisible: false, //对话框的开关
      //对话框的表单内容
      form: {
        cardNum: "", //会员卡号
        name: "", //会员名称
        birthday: "", //会员生日
        phone: "", //手机号码
        integral: "", //可用积分
        money: "", //开卡金额
        payType: "", //支付方式
        address: "" //地址
      },
      formLabelWidth: "120px",
      rules: {
        //手机号正则验证
        phone: [{ required: true, validator: checkPhone, trigger: "blur" }],
        //会员名称验证
        name: [
          { required: true, message: "请输入会员名称", trigger: "blur" },
          { min: 2, max: 5, message: "长度在 2 到 5 个字符", trigger: "blur" }
        ],
        //会员卡号验证
        cardNum: [
          { required: true, message: "请输入会员卡号", trigger: "blur" }
        ]
      }
      // id: '' //编辑单条数据的id，对话框的复用条件
    };
  },
  created() {
    this.getSearch(); //进入就调用数据（会员数据分页列表）
  },
  watch: {
    //监听对话框，取消再次打开保留的校验结果
    dialogFormVisible: function(val, oldVla) {
      if (!val) {
        //关闭对话框时
        this.$refs.form.clearValidate();
      }
    }
  },
  methods: {
    //查询按钮
    onSubmit() {
      this.getSearch(); //查询同时分页渲染
    },
    //重置按钮
    resetForm(formInline) {
      this.$refs[formInline].resetFields();
    },
    // 新增按钮
    addMember() {
      this.dialogFormVisible = true;
      this.form = {
        //新增的时候，窗口打开之前，清除表单数据和校验提示
        cardNum: "",
        name: "",
        birthday: "",
        phone: "",
        money: "",
        integral: "",
        payType: "",
        address: ""
      };
    },
    submitInfo(form) {
      // 对话框：新增表单验证方法
      this.$refs.form.validate(
        function(result) {
          if (result) {
            // 验证通过
            this.addMem();
            // console.log(form);
          } else {
          } // 验证不通过
        }.bind(this)
      );
    },
    //新增验证成功后发送请求
    async addMem() {
      // console.log(this.form);
      try {
        let p = await memberApi.getMember(this.form); //把新增会员的数据传到后端
        if (p.data.flag) {
          this.$message({
            //成功弹窗
            message: p.data.message,
            type: "success"
          });
          this.dialogFormVisible = false; //关闭对话框
        } else {
          this.$message.error("添加失败");
        }
      } catch (err) {
        console.log(err);
      }
    },
    //表格编辑按钮
    handleEdit(index, row) {
      this.dialogFormVisible = true;
      this.form = JSON.parse(JSON.stringify(row)); //编辑时会员列表不发生改变
    },
    //编辑表格验证
    editMember(form) {
      this.$refs.form.validate(
        function(result) {
          if (result) {
            // 验证通过
            this.editMem();
          } else {
          } // 验证不通过
        }.bind(this)
      );
    },
    //编辑：表格验证成功后发送请求
    async editMem() {
      try {
        let p = await memberApi.putMember(this.form);
        if (p.data.flag) {
          //请求成功
          this.$message({
            message: p.data.message,
            type: "success"
          });
          this.dialogFormVisible = false; //关闭对话框
        } else {
          this.$message.error("修改失败");
        }
      } catch (err) {
        console.log(err);
      }
    },
    // 表格删除按钮
    handleDelete(index, row) {
      if (confirm("确定要删除吗")) {
        this.removeMember(row.id); //删除
      }
    },
    //请求删除
    async removeMember(id) {
      try {
        let p = await memberApi.removeMem(id);
        if (p.data.flag) {
          this.$message({
            //成功弹窗
            message: p.data.message,
            type: "success"
          });
        } else {
          this.$message.error(p.data.message);
        }
      } catch (err) {
        console.log(err);
      }
    },
    // 分页
    async getSearch() {
      try {
        let p = await memberApi.search(
          this.currentPage,
          this.pagesize,
          this.formInline
        ); //获取响应数据
        //支付类型替换掉数字
        p.data.data.rows.forEach(item => {
          this.payTypeOptions.forEach(ite => {
            if (ite.type == item.payType) {
              item.payType = ite.name;
            }
          });
        });
        this.tableData = p.data.data.rows; //数据渲染
        this.total = p.data.data.total; //总条数
      } catch (err) {
        console.log(err);
      }
    },
    //每页显示多少条
    handleSizeChange(val) {
      // console.log(`每页 ${val} 条`);
      this.pagesize = val;
      this.getSearch();
    },
    //切换，当前页是哪页
    handleCurrentChange(val) {
      // console.log(`当前页: ${val}`);
      this.currentPage = val;
      this.getSearch();
    }
  },
  components: {}
};
</script>

<style scoped lang="scss">
//分页按钮样式
.block {
  text-align: center;
  margin-top: 20px;
}
.el-dialog .el-dialog__body {
  padding: 30px 60px 0px 20px;
}
</style>